package xin.marcher.module.construction.remote;

import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Component;
import xin.marcher.module.common.constants.ParticipantTypeConstant;
import xin.marcher.module.common.core.JsonResult;
import xin.marcher.module.common.exception.BaseBizException;
import xin.marcher.module.construction.builder.FullProductData;
import xin.marcher.module.construction.domain.entity.SkuInfoDO;
import xin.marcher.module.label.api.ProductLabelRelationApi;
import xin.marcher.module.label.domain.dto.ProductLabelRelationResultDTO;
import xin.marcher.module.label.domain.request.ProductLabelRelationRequest;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 商品标签 API
 */
@Component
public class ProductLabelRemote {

    @DubboReference(version = "1.0.0")
    private ProductLabelRelationApi productLabelRelationApi;

    /**
     * 保存商品标签
     */
    public void saveProductLabels(FullProductData fullProductData) {

        String itemId = fullProductData.getItemInfoDO().getItemId();
        List<String> skuIds = fullProductData.getSkuInfoDOList().stream().map(SkuInfoDO::getSkuId).collect(Collectors.toList());
        List<Long> labelIds = fullProductData.getLabelIds();

        List<ProductLabelRelationRequest> list = new ArrayList<>();
        // 把每个标签都贴到item上，以及所有的sku上
        for (Long labelId : labelIds) {
            ProductLabelRelationRequest request = new ProductLabelRelationRequest(itemId, ParticipantTypeConstant.PARTICIPANT_TYPE_ITEM, labelId);
            list.add(request);

            for (String skuId : skuIds) {
                ProductLabelRelationRequest request2 = new ProductLabelRelationRequest(skuId, ParticipantTypeConstant.PARTICIPANT_TYPE_SKU, labelId);
                request2.setLabelId(labelId);
                list.add(request2);
            }
        }

        JsonResult<ProductLabelRelationResultDTO> result = productLabelRelationApi.saveProductLabelRelation(list);
        if (!result.getSuccess()) {
            throw new BaseBizException("保存商品标签发生异常");
        }
    }

}
